//
//  SSUserInfo.swift
//  MyMicroBlog
//
//  Created by stevenSu on 15/7/30.
//  Copyright © 2015年 stevenSu. All rights reserved.
//

import UIKit
import SDWebImage

class SSUserInfo: NSObject {
    // 友好显示名称
    var name: String?
    // 用户头像地址（大图），180×180像素
    var avatar_large: String?
    // 用户头像
    var avatar_large_image: UIImage?
    
    func loadUserInfo(completion: SSCompletionCallBack) {
        let userdefault = NSUserDefaults.standardUserDefaults()
        name = userdefault.objectForKey("name") as? String ?? nil
        avatar_large = userdefault.objectForKey("avatar_large") as? String ?? nil
        // 判断如果头像路径存在且沙盒有缓存图片
        if name != nil && avatar_large != nil && SDWebImageManager.sharedManager().cachedImageExistsForURL(NSURL(string: avatar_large!)!) {

            print("从本地获取用户信息 ")
            // 从缓存取图片
            completion(result: nil, error: nil)
            return
        }
        
        // 从服务器下载
        SSNetworkTools.sharedNetworkTools.loadUserInfo({ (result, error) -> () in
            print("从服务器获取用户信息")
            if let data = result {
                self.name = data["name"] as? String
                self.avatar_large = data["avatar_large"] as? String
                completion(result: data, error: nil)
                userdefault.setObject(self.avatar_large, forKey: "avatar_large")
                userdefault.setObject(self.name, forKey: "name")
            } else {
                print(error)
                completion(result: nil, error: error)
            }
        })
    }
    
    override var description: String {
        let dict = dictionaryWithValuesForKeys(["name", "avatar_large"])
        return "\(dict)"
    }
}
